let timer = null

function WebSocketProxy (url,vm) {
  this.url = url 
  this.socket = undefined
  this.vm = vm
}

WebSocketProxy.prototype.create = function createSocket () {
  if (!WebSocket) {
    console.log('Sorry! Your browser doesn\'t support WebSocket')
    return
  }
  if (this.socket) {
    console.log('Connection already exist')
    console.log(this.socket)
    return
  }

  try {
    this.socket = new WebSocket(this.url)
    const self = this
    // 连接错误
    this.socket.onerror = function (e) {
      console.log('on error')
      self.close()
      timer && clearInterval(timer)
      timer = null
    }
    // 消息通知
    this.socket.onmessage = function ({data:msg}) {
      jsonMsg = JSON.parse(msg)

      switch(jsonMsg.type){
        case 'open':
          timer = setInterval(() => {
            self.send({type:'ping'})
          },1000 * 30)
          break;
        case "close":
          self.close() 
          break;
        case 'ping':
          break;
        default:
          if(jsonMsg.filename) {
            if(self.vm.messageObj[jsonMsg.filename]){
              self.vm.messageObj[jsonMsg.filename].push(jsonMsg.data)
            }else{
              self.vm.messageObj[jsonMsg.filename] = [jsonMsg.data]
            }
            // message({ 
            //     message: jsonMsg.data+'--'+jsonMsg.filename,
            //     type: jsonMsg.type == 'error' ? 'error' : '',
            // }) 
            if(jsonMsg.data.indexOf('打包结束') != -1){
              self.vm.init()
            }
          }else{
            if(jsonMsg.type == 'log'){
              message({ 
                message: jsonMsg.data,
              })
              if(jsonMsg.data.indexOf('SDK更新成功') != -1){
                // self.vm.sdkData
              }
            }
            console.log(jsonMsg.data)

          }
          break;
      }
    }
  } catch (err) {
    console.log(err)
    this.close()
  }
}

WebSocketProxy.prototype.send = function sendMessage (msg) {
  if (!this.socket || this.socket.readyState !== 1) {
    return closeSocket()
  }
  msg = msg || {type:'default',data:'default message'}
  this.socket.send(JSON.stringify(msg))
}

function closeSocket () {
  this.socket ? this.socket.close && this.socket.close() : ''
  this.socket = undefined
  timer && clearInterval(timer)
  timer = null
}

WebSocketProxy.prototype.close = closeSocket

